package modules

import (
	"github.com/druidcaesa/gotool"
	"github.com/fogleman/gg"
	"os"
	"path/filepath"
	"strings"
	"time"
	"virchow_poster/utils"
)

type Poster struct {
	Width          int      `json:"Width"`
	Height         int      `json:"Height"`
	BackgroudColor string   `json:"backgroudColor"`
	BackgroudImage string   `json:"backgroudImage"`
	Images         []Images `json:"images"`
	Words          []Words  `json:"words"`
	Lines          []Lines  `json:"lines"`
	SavePath       string   `json:"SavePath"`
	SaveName       string   `json:"SaveName"`
}

const (
	DefaultBgColor    = "#FFFFFF"
	DefaultFontFamily = "./resource/msyh.ttf"
)

// 创建画布
func createCanvas(poster *Poster) (canvas *gg.Context) {
	if gotool.StrUtils.HasNotEmpty(poster.BackgroudImage) {
		// 以背景图片为主
		// 判断图片地址是本地路径还是网络路径， 网络地址的话需要下载图片到本地才能使用
		// 根据设置，判断是否将图片强制缩放到画布大小
		// 从图片中创建画布
		var localFilePath string
		if strings.HasPrefix(strings.ToLower(strings.TrimSpace(poster.BackgroudImage)), "http") {
			localFilePath = utils.SaveHttpImage(poster.BackgroudImage, poster.SavePath+"/downloads", time.Now().Format("20060102150405.000000"))
		}
		backgroudImage, _ := gg.LoadImage(localFilePath)
		defer func() {
			// TODO :: 删除下载的缓存图片
			//os.Remove(localFilePath)
		}()
		canvas = gg.NewContextForImage(backgroudImage)
	} else {
		// 以背景色为主
		canvas = gg.NewContext(poster.Width, poster.Height)
		canvas.SetHexColor(poster.BackgroudColor)
		canvas.Clear()
	}
	return
}

// 保存海报到指定路径
func savePoster(poster *Poster, canvas *gg.Context) {
	os.MkdirAll(filepath.Join(poster.SavePath, "results"), 0777)
	os.Chmod(filepath.Join(poster.SavePath, "results"), 0777)
	canvas.SavePNG(filepath.Join(poster.SavePath, "results", poster.SaveName))
}
